/*
  	Arkodroid - An Arduino Controller for Android
	Copyright (c) 2013 Miguel Monteiro, Eduardo Peixoto, Rui Pedro Carvalhal, André Braga.
	All rights reserved.
	http://code.google.com/p/arkodroid/
	
	Amarino API by Bonifaz Kaufmann - http://www.amarino-toolkit.net/
	
	This program is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

package net.miguelmonteiro.android.arkodroid;

import net.miguelmonteiro.android.arkodroid.Checker.Resource;
import android.app.Activity;
import android.content.Intent;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import at.abraxas.amarino.Amarino;

public class ArkodroidAccelerometer extends Activity implements SensorEventListener {
	// Variables
	static long lastchanged;
	
	public static final String TAG = "ArkodroidAccelerometer";
	static Activity ACTIVITY;
	
	private SensorManager sensorManager;
	
	// Declare objects
	TextView xCoor;
	TextView yCoor;
	
    ImageView arrowUp;
    ImageView arrowDown;
    ImageView arrowLeft;
    ImageView arrowRight;
    
    Button buzzerButton;
    ToggleButton toggleButton;
	
    /** Check if Bluetooth is ON **/
	@Override 
    protected void onResume() {
		super.onResume();
		
    	new Checker(this).pass(new Checker.Pass() {
    		@Override public void pass() {
    	    	// Nothing
    	 	}
    	}).check(Resource.BLUETOOTH);
    }

    /** Called when the activity is first created. **/
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        setContentView(R.layout.main);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        ACTIVITY = this;
        lastchanged = System.currentTimeMillis();
    	
    	sensorManager=(SensorManager)getSystemService(SENSOR_SERVICE);
		// Add listener. The listener will be HelloAndroid (this) class
		sensorManager.registerListener(this, 
				sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
				SensorManager.SENSOR_DELAY_GAME);
        
        // Create objects
        xCoor = (TextView)findViewById(R.id.xcoor);
		yCoor = (TextView)findViewById(R.id.ycoor);
		buzzerButton = (Button) findViewById(R.id.buttonBuzzer);
		toggleButton = (ToggleButton) findViewById(R.id.ToggleButton01);
		
		buzzerButton.setOnClickListener(new View.OnClickListener() {
	        public void onClick(View v) {
	        	if (Arkodroid.bdIsConnected == true) {
		        	Log.i(TAG, "Buzzer command sent");
		        	Amarino.sendDataToArduino(ArkodroidAccelerometer.this, BluetoothConnect.DEVICE_ADDRESS, 'b', (1));
	        	}
	        	else {
	                Toast.makeText(ArkodroidAccelerometer.this, "Não connectado.", Toast.LENGTH_SHORT).show();
	        	}
	        }
	    });
    }

	public void onAccuracyChanged(Sensor sensor,int accuracy){
		// Nothing
	}
	
	/** Get the values of the Accelerometer **/
	public void onSensorChanged(SensorEvent event){		
		// Check sensor type
		if(event.sensor.getType()==Sensor.TYPE_ACCELEROMETER){			
			// Get X and Y accelerometer values (we won't use Z).
			// Use Math.round(Var) to get an Int value
			int x = Math.round(event.values[0]);
			int y = Math.round(event.values[1]);
			Arkodroid.values[0] = Integer.toString(x);
			Arkodroid.values[1] = Integer.toString(y);
			
			// Set X and Y to textView
			xCoor.setText("X: " + x);
			yCoor.setText("Y: " + y);
			
			// Change Arrow colors
			ChangeArrows(x, y);
			
			if (System.currentTimeMillis() - lastchanged > Arkodroid.delay){
				Amarino.sendDataToArduino(ArkodroidAccelerometer.this, BluetoothConnect.DEVICE_ADDRESS, 'A', Arkodroid.values.clone());
				lastchanged = System.currentTimeMillis();
			}
		}
	}
	
	/** Change the Arrows color with the Accelerometer values **/
	public void ChangeArrows(int X, int Y) {
		arrowDown = (ImageView) findViewById(R.id.ArrowDown);
        arrowUp = (ImageView) findViewById(R.id.ArrowUp);
        arrowRight = (ImageView) findViewById(R.id.ArrowRight);
		arrowLeft = (ImageView) findViewById(R.id.ArrowLeft);

		// 		X Coord
		// Between "X" Thresholds
		if (X > -Arkodroid.threshold && X < Arkodroid.threshold) {
	        arrowUp.setImageResource(R.drawable.arrow);
	        arrowDown.setImageResource(R.drawable.arrow);			
		}
		
		// Threshold <= X <= 10 
		else if (X >= Arkodroid.threshold && X < Arkodroid.threshold + 3) {
	        arrowUp.setImageResource(R.drawable.arrow);
	        arrowDown.setImageResource(R.drawable.arrowmin);
		}
		else if (X >= Arkodroid.threshold + 3 && X < 9) {
	        arrowUp.setImageResource(R.drawable.arrow);
	        arrowDown.setImageResource(R.drawable.arrowmed);
		}
		else if (X >= 9) {
	        arrowUp.setImageResource(R.drawable.arrow);
	        arrowDown.setImageResource(R.drawable.arrowmax);
		}
		
		// -Threshold >= X >= -10 
		else if (X <= -Arkodroid.threshold && X > -Arkodroid.threshold - 3) {
	        arrowDown.setImageResource(R.drawable.arrow);
	        arrowUp.setImageResource(R.drawable.arrowmin);
		}
		else if (X <= -Arkodroid.threshold - 3 && X > -9) {
			arrowDown.setImageResource(R.drawable.arrow);
	        arrowUp.setImageResource(R.drawable.arrowmed);
		}
		else if (X <= -9) {
			arrowDown.setImageResource(R.drawable.arrow);
	        arrowUp.setImageResource(R.drawable.arrowmax);
		}
		
		// 		Y Coord
		// Between "Y" Thresholds
		if (Y > -Arkodroid.threshold && Y < Arkodroid.threshold) {
	        arrowRight.setImageResource(R.drawable.arrow);
	        arrowLeft.setImageResource(R.drawable.arrow);			
		}
		
		// Threshold <= X <= 10 
		else if (Y >= Arkodroid.threshold && Y < Arkodroid.threshold + 3) {
			arrowLeft.setImageResource(R.drawable.arrow);
			arrowRight.setImageResource(R.drawable.arrowmin);
		}
		else if (Y >= Arkodroid.threshold + 3 && Y < 9) {
			arrowLeft.setImageResource(R.drawable.arrow);
			arrowRight.setImageResource(R.drawable.arrowmed);
		}
		else if (Y >= 9) {
			arrowLeft.setImageResource(R.drawable.arrow);
			arrowRight.setImageResource(R.drawable.arrowmax);
		}
		
		// -Threshold >= X >= -10 
		else if (Y <= -Arkodroid.threshold && Y > -Arkodroid.threshold - 3) {
			arrowRight.setImageResource(R.drawable.arrow);
			arrowLeft.setImageResource(R.drawable.arrowmin);
		}
		else if (Y <= -Arkodroid.threshold - 3 && Y > -9) {
			arrowRight.setImageResource(R.drawable.arrow);
			arrowLeft.setImageResource(R.drawable.arrowmed);
		}
		else if (Y <= -9) {
			arrowRight.setImageResource(R.drawable.arrow);
			arrowLeft.setImageResource(R.drawable.arrowmax);
		}
	}
	
	public void onToggleClicked(View v) {
		Arkodroid.doLightToggleClick(this, v);
    }
	
	/** Hard "Back button" pressed **/
	@Override
    public void onBackPressed() {
		Arkodroid.exit(this);
    }
    
	/** Menu creation **/
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.layout.menu, menu);        
        return true;
    }
    
	@Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        	case R.id.connecttext:
            	startActivity(new Intent(this, BluetoothConnect.class));                
            	return true;
        	case R.id.musictext:
        		Arkodroid.selectMusic(this);
        		return true;
            case R.id.settingstext:
            	finish();
            	startActivity(new Intent(this, net.miguelmonteiro.android.arkodroid.Settings.class));
                return true;
            case R.id.abouttext:
                Arkodroid.aboutDialog(this);
                return true;
        }
        return true;
    }
}
